/*
 * Copyright (C) 2023 HiHope Open Source Organization .
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

 #include <stdio.h>
 #include <unistd.h>
 
 #include "ohos_init.h"
 #include "cmsis_os2.h"
 #include "iot_gpio.h"
 #include "iot_pwm.h"
 #include "iot_errno.h"
 #include "hi_io.h"
 
 #define MAX_DUTY_CYCLE 100
 #define PWM_FREQ_VALUE 64000
 #define STEP_DELAY 17500       // 调整后的步进延时
 #define TASK_STACK_SIZE 4096
 #define RED_PWM_CHANNEL 2
 #define GREEN_PWM_CHANNEL 1
 #define BLUE_PWM_CHANNEL 0
 #define TOTAL_CYCLES 3
 
 /* 配置LED的PWM通道 */
 static void ConfigurePWMChannel(int gpioPin, int pwmChannel)
 {
     IoTGpioInit(gpioPin);
     IoTGpioSetDir(gpioPin, IOT_GPIO_DIR_OUT);
     hi_io_set_func(gpioPin, 5);
     IoTPwmInit(pwmChannel);
 }
 
 static void SmoothBreathingEffect(int channel, int gpioPin)
 {
     ConfigurePWMChannel(gpioPin, channel);
     
     // 渐亮阶段
     for (int duty = 1; duty <= MAX_DUTY_CYCLE; duty++) {
         IoTPwmStart(channel, duty, PWM_FREQ_VALUE);
         usleep(STEP_DELAY);
     }
     
     // 渐暗阶段
     for (int duty = MAX_DUTY_CYCLE; duty >= 1; duty--) {
         IoTPwmStart(channel, duty, PWM_FREQ_VALUE);
         usleep(STEP_DELAY);
     }
     
     IoTPwmStop(channel);
 }
 
 static void BreathingLightTask(void)
 {
     static int cycleCount = TOTAL_CYCLES;
 
     while (cycleCount--) {
         SmoothBreathingEffect(RED_PWM_CHANNEL, 2);
         SmoothBreathingEffect(GREEN_PWM_CHANNEL, 8);
         printf("Smooth breathing effect running...\n");
         SmoothBreathingEffect(BLUE_PWM_CHANNEL, 7);
     }
 }
 
 static void StartBreathingTask(void)
 {
     osThreadAttr_t taskConfig = {
         .name = "BreathingTask",
         .stack_size = TASK_STACK_SIZE,
         .priority = osPriorityNormal
     };
 
     if (osThreadNew(BreathingLightTask, NULL, &taskConfig) == NULL) {
         printf("[BreathingLight] Task creation failed!\n");
     }
 }
 
 APP_FEATURE_INIT(StartBreathingTask);